package com.snail.billing.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.net.HttpApp;
import com.android.net.HttpConst;
import com.android.net.HttpResult;
import com.android.net.HttpSession;
import com.android.net.OnHttpResultListener;
import com.android.os.Page;
import com.android.util.AlertUtil;
import com.android.util.ResUtil;
import com.snail.billing.DataCache;
import com.snail.billing.Resource;
import com.snail.billing.UserCenterType;
import com.snail.billing.data.Account;
import com.snail.billing.data.AccountManager;
import com.snail.billing.fragment.view.UserCenterAdapter;
import com.snail.billing.json.JsonGeneralLogin;
import com.snail.billing.json.JsonValidateInfo;
import com.snail.billing.net.BillingHttpApp;
import com.snail.billing.session.GeneralLoginSession;
import com.snail.billing.session.ValidateInfoSession;

public class UserCenterFragment extends Page implements View.OnClickListener, AdapterView.OnItemClickListener, OnHttpResultListener {

	private TextView textTitle;
	private View buttonBack;

	private View layout;
	private TextView textAccount;

	private ListView listView;
	private List<UserCenterAdapter.AdapterData> data;
	private Account account;

	private List<Integer> userCenterTypes;

	private HttpApp httpApp;
	private GeneralLoginSession generalLoginSession;

	private int validateInfoState;
	private ValidateInfoSession validateInfoSession;
	private JsonValidateInfo jsonValidateInfo;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_user_center_activity);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		textTitle = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_text));
		textTitle.setText(ResUtil.getString(Resource.string.snailbilling_user_center_title));
		buttonBack = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_back));
		buttonBack.setOnClickListener(this);
		//
		layout = findViewById(ResUtil.getViewId(Resource.id.snailbilling_user_center_layout));
		layout.setVisibility(View.GONE);
		textAccount = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_user_center_text_account));
		listView = (ListView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_user_center_list_view));
		listView.setOnItemClickListener(this);
		data = new ArrayList<UserCenterAdapter.AdapterData>();
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_nickname), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_nickname)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_mobile), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_mobile)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_email), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_email)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_password), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_pwd)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_change), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_change)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_question), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_question)));
		data.add(new UserCenterAdapter.AdapterData(ResUtil.getDrawableId(Resource.drawable.snailbilling_phone), ResUtil.getStringId(Resource.string.snailbilling_user_center_text_phone)));
		//
		httpApp = new HttpApp(getContext());
		httpApp.setOnHttpResultListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		account = AccountManager.getCurrentAccount();
		textAccount.setText(ResUtil.getString(Resource.string.snailbilling_user_center_current_account) + DataCache.getInstance().importParams.account);
		if (DataCache.getInstance().importParams.aid == null) {
			requestGeneralLogin();
		} else {
			initList();
		}
	}

	private void initList() {
		if (this.account != null) {
			userCenterTypes = new ArrayList<Integer>();
			int[] temp = DataCache.getInstance().userCenterTypes;
			for (int i = 0; i < temp.length; i++) {
				if (temp[i] != 0 || account.getType().equals("1")) {
					userCenterTypes.add(temp[i]);
				}
			}
			UserCenterAdapter adapter = new UserCenterAdapter(data, userCenterTypes);
			listView.setAdapter(adapter);
			layout.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(buttonBack)) {
			getPageManager().backward();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		int type = userCenterTypes.get(position);
		switch (type) {
			case UserCenterType.CONFIG_NICKNAME:
				getPageManager().forward(NicknameFragment.class);
			break;
			case UserCenterType.BIND_MOBILE:
				functionFactory(1);
			break;
			case UserCenterType.BIND_EMAIL:
				functionFactory(2);
			break;
			case UserCenterType.MODIFY_PASSWORD:
				functionFactory(3);
			break;
			case UserCenterType.CHANGE_ACCOUNT:
				getPageManager().forward(LoginFragment.class);
			break;
			case UserCenterType.ONLINE_QUESTION:
				getPageManager().forward(WorkMainFragment.class);
			break;
			case UserCenterType.CUSTON_SERVICE_PHONE:
				getPageManager().forward(PhoneFragment.class);
			break;
		}
	}

	private void functionFactory(int validateInfoState) {
		this.validateInfoState = validateInfoState;
		if (account.getType().equals("1")) {
			AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
			builder.setMessage(ResUtil.getString(Resource.string.snailbilling_user_center_random_account));
			builder.setPositiveButton(ResUtil.getString(HttpConst.string.NET_OK), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					getPageManager().forward(NicknameFragment.class);
				}
			});
			builder.show();
		} else {
			if (jsonValidateInfo != null) {
				switch (validateInfoState) {
					case 1:
						functionBindMoblie();
					break;
					case 2:
						functionBindEmail();
					break;
					case 3:
						functionModifyPassword();
					break;
				}
			} else {
				requestValidateInfo();
			}
		}
	}

	private void functionBindMoblie() {
		if (jsonValidateInfo.getIsMobileAuthed()) {
			String message = String.format(ResUtil.getString(Resource.string.snailbilling_user_center_have_bind_mobile), showMobile(jsonValidateInfo.getMobile()));
			AlertUtil.show(getContext(), message);
		} else {
			jsonValidateInfo = null;
			getPageManager().forward(MobileBindFragment.class);
		}
	}

	private void functionBindEmail() {
		if (jsonValidateInfo.getIsEmailAuthed()) {
			String message = String.format(ResUtil.getString(Resource.string.snailbilling_user_center_have_bind_email), showEmail(jsonValidateInfo.getEmail()));
			AlertUtil.show(getContext(), message);
		} else {
			jsonValidateInfo = null;
			getPageManager().forward(EmailBindFragment.class);
		}
	}

	private void functionModifyPassword() {
		if (jsonValidateInfo.getIsMobileAuthed() || jsonValidateInfo.getIsEmailAuthed()) {
			goToPassword();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
			builder.setMessage(ResUtil.getString(Resource.string.snailbilling_user_center_no_bind));
			builder.setPositiveButton(ResUtil.getString(HttpConst.string.NET_OK), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					goToPassword();
				}
			});
			builder.show();
		}
	}

	private void goToPassword() {
		jsonValidateInfo = null;
		Bundle args = new Bundle();
		args.putString("account", account.getAccount());
		if (account.getType().equals("1")) {
			args.putInt("state", PasswordFragment.MODIFY_PWD_RANDOM);
			args.putString("pwd", account.getPwd());
		} else {
			args.putInt("state", PasswordFragment.MODIFY_PWD);
		}
		getPageManager().forward(PasswordFragment.class, args);
	}

	private void requestGeneralLogin() {
		generalLoginSession = new GeneralLoginSession(account.getAccount(), account.getPwd());
		httpApp.request(generalLoginSession);
	}

	private void requestValidateInfo() {
		BillingHttpApp billingHttpApp = new BillingHttpApp(getContext(), new BillingHttpApp.RequestHttpSesssionListener() {

			@Override
			public HttpSession getLoginHttpSession() {
				return new GeneralLoginSession(account.getAccount(), account.getPwd());
			}

			@Override
			public HttpSession getRequestHttpSesssion() {
				validateInfoSession = new ValidateInfoSession();
				return validateInfoSession;
			}
		});
		billingHttpApp.setOnHttpResultListener(this);
		billingHttpApp.request();
	}

	@Override
	public void onHttpResult(HttpResult httpResult) {
		if (httpResult.isSucceed()) {
			HttpSession httpSession = httpResult.getHttpSession();
			if (httpSession.equals(generalLoginSession)) {
				JsonGeneralLogin jsonGeneralLogin = new JsonGeneralLogin((String) generalLoginSession.getResponseData());
				if (!TextUtils.isEmpty(jsonGeneralLogin.getSessionId())) {
					DataCache.getInstance().importParams.sessionId = jsonGeneralLogin.getSessionId();
				}
				if (jsonGeneralLogin.getCode() == 1) {
					if (!TextUtils.isEmpty(jsonGeneralLogin.getSessionId())) {
						DataCache.getInstance().importParams.aid = jsonGeneralLogin.getAid();
						initList();
					} else {
						Toast.makeText(getContext(), ResUtil.getString(Resource.string.snailbilling_login_fail), Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(getContext(), jsonGeneralLogin.getMessage(), Toast.LENGTH_SHORT).show();
				}
			} else if (httpSession.equals(validateInfoSession)) {
				jsonValidateInfo = new JsonValidateInfo((String) validateInfoSession.getResponseData());
				if (!TextUtils.isEmpty(jsonValidateInfo.getSessionId())) {
					DataCache.getInstance().importParams.sessionId = jsonValidateInfo.getSessionId();
				}
				if (jsonValidateInfo.getCode() == 1) {
					if (validateInfoState == 1) {
						functionBindMoblie();
					} else if (validateInfoState == 2) {
						functionBindEmail();
					} else if (validateInfoState == 3) {
						functionModifyPassword();
					}
				} else {
					Toast.makeText(getContext(), jsonValidateInfo.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private String showMobile(String mobile) {
		if (TextUtils.isEmpty(mobile)) {
			return "";
		}
		StringBuilder builder = new StringBuilder();
		char[] chars = mobile.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (i < 3 || i > chars.length - 4) {
				builder.append(chars[i]);
			} else {
				builder.append("*");
			}
		}
		return builder.toString();
	}

	private String showEmail(String email) {
		if (TextUtils.isEmpty(email)) {
			return "";
		}
		String[] strs = email.split("@");
		StringBuilder builder = new StringBuilder();
		char[] chars = strs[0].toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (i < 3) {
				builder.append(chars[i]);
			} else {
				builder.append("*");
			}
		}
		builder.append("@");
		builder.append(strs[1]);
		return builder.toString();
	}

}
